"""
Example definition of a macro that is granted friend visibility privileges to
interoperate with another macro. Also demonstrates a finalizer that wraps it.
"""

def _impl(name, visibility, deps, out, _aggregate_tool):
    native.genrule(
        name = name,
        visibility = visibility,
        outs = [out],
        tools = [_aggregate_tool],
        # We generally try to avoid string manipulation on labels to derive
        # other labels, but sometimes it's necessary. In this case we're
        # obtaining the internal <name>_letter_freq targets of the given
        # count_words macro instances. We can see these internal targets
        # in this macro because our package is specifically granted visibility
        # by those in the definition of count_words.
        srcs = [str(d) + "_letter_freq" for d in deps],
        cmd = "$(location %s) $(SRCS) > $@" % str(_aggregate_tool),
    )

generate_letter_frequencies = macro(
    implementation = _impl,
    attrs = {
        "deps": attr.label_list(mandatory = True, configurable = False),
        "out": attr.output(mandatory = True),
        "_aggregate_tool": attr.label(default = ":aggregate.py", configurable = False),
    },
    doc = """
    Emits a file summarizing letter frequency data generated by the count_words
    macro. Each dep is the label of a main target of a count_words macro
    instance.
    """,
)

def _gather_impl(name, visibility, out):
    suffix = "_letter_freq"
    deps = []
    for target_name in native.existing_rules():
        if target_name.endswith(suffix):
            # Infer count_words macro name from matched target name.
            deps.append(":" + target_name[:-len(suffix)])

    generate_letter_frequencies(
        name = name,
        visibility = visibility,
        deps = deps,
        out = out,
    )

gather_all_letter_frequencies = macro(
    implementation = _gather_impl,
    attrs = {
        "out": attr.output(mandatory = True),
    },
    finalizer = True,
    doc = """
    Convenience finalizer form of generate_letter_frequencies, that
    automatically infers deps by grabbing targets named *_letter_freq
    from the current package.
    """,
)
